package cn.labbook.bluetooth.controller;


import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.entity.AdminRes;
import cn.labbook.bluetooth.service.IAdminResService;
import cn.labbook.bluetooth.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Condition;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lonzy
 * @since 2019-03-26
 */
@Controller
@RequestMapping("//adminRes")
public class AdminResController extends AbstractController {
    @Autowired
    IAdminResService adminResService;
    @RequestMapping("/save")
    public ResultDto add(@RequestBody List<AdminRes> rolePrivileges) {
        List<AdminRes> realRolePrivileges = rolePrivileges
                .stream()
                .filter(i -> StringUtils.isNotBlank(i.getAdminId()))
                .collect(Collectors.toList());
        List<String> roleIds = realRolePrivileges
                .stream()
                .map(rolePrivilege -> rolePrivilege.getAdminId())
                .distinct()
                .collect(Collectors.toList());
        roleIds.forEach(roleId -> {
            LambdaQueryWrapper<AdminRes> lambda = Condition.lambda();
            lambda.eq(AdminRes::getAdminId, roleId);
            adminResService.remove(lambda);
            List<AdminRes> batchList = realRolePrivileges
                    .stream()
                    .filter(i -> {
                        if (roleId.equals(i.getAdminId())) {
                            return StringUtils.isNotBlank(i.getAdminId(), i.getResourceId());
                        } else
                            return false;
                    })
                    .collect(Collectors.toList());
            if (!batchList.isEmpty())
                adminResService.saveBatchWithCache(roleId, batchList);
        });
        return success();
    }
}
